package com.ssb.admin.common.utils;

import com.ssb.admin.common.exception.ApiException;
import com.ssb.admin.config.UploadConfigure;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Encoder;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

/**
 * @author duaichao
 * @since 2018/9/28 10:57
 */
@Slf4j
public class UploadUtils {

    public static String uploadFile(MultipartFile file){

        String res = "";
        String basePath = ((UploadConfigure)SpringContextUtils.getBean("uploadConfigure")).getBasePath();
        String folder = FileUtils.getFolder();
        String fileName = FileUtils.getFileName() + FileUtils.getFileNameSub(file.getOriginalFilename());
        try {
            Files.createDirectories(Paths.get(basePath, folder));
            Path fullPath = Paths.get(basePath, folder, fileName);
            Files.write(fullPath, file.getBytes(), StandardOpenOption.CREATE);
            res = folder+fileName;
            log.info("访问路径：", res);
        } catch (Exception e) {
            Path path = Paths.get(folder);
            log.error("写入文件异常,删除文件：", e);
            try {
                Files.deleteIfExists(path);
            } catch (IOException e1) {
                throw new ApiException("上传文件失败");
            }
        }
        return res;
    }

    /**
     * 图片文件存储
     */
    public static String uploadBase64File(MultipartFile file){
        byte[] data;
        try{
            data = file.getBytes();
        }catch (IOException e){
            throw new ApiException("上传文件失败");
        }
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(data);
    }
}
